﻿using System.ComponentModel;
using HelloWorld.Shared.LocalServiceReference;

namespace HelloWorld.Shared.Models
{
    /// <summary>
    /// The main model for the silverlight application
    /// </summary>
    public class MainPageModel : INotifyPropertyChanged
    {
        private string _result;
        private StuffTodo _stufftodo;
        private int _processingCounter;

        public enum StuffTodo
        {
            Nothing,
            Eat,
            Sleep,
            Drink,
            BeMerry,
            AllOfTheAbove
        }

        public bool IsProcessing
        {
            get
            {
                return _processingCounter != 0;
            }
            
            set
            {
                if (value)
                    _processingCounter++;
                else
                    _processingCounter--;
            }
        }

        /// <summary>
        /// Gets or sets what you'd like to do today
        /// </summary>
        public StuffTodo Todo
        {
            get
            {
                return _stufftodo;
            }

            set
            {
                if (value != _stufftodo)
                {
                    _stufftodo = value;
                    Notify("Todo");
                }
            }
        }

        /// <summary>
        /// Gets or sets the result of what you did today
        /// </summary>
        public string Result
        {
            get
            {
                return _result;
            }

            set
            {
                _result = value;
                Notify("Result");
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        public void Doit()
        {
            var service = new DoSomethingServiceSoapClient();
            service.DoSomethingCompleted += service_DoSomethingCompleted;
            IsProcessing = true;
            service.DoSomethingAsync(Todo.ToString().ToLower());
        }

        private void service_DoSomethingCompleted(object sender, DoSomethingCompletedEventArgs e)
        {
            IsProcessing = false;
            Result = e.Result;
        }

        private void Notify(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }
}
